import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutter_trip/Model/CommonItemModel.dart';

/// 忽略名单
final List<String> ignoreURLs = [
  'm.ctrip.com/',
  'm.ctrip.com/html5/',
  'm.ctrip.com/html5',
  'webapp/dingzhi/index',
  'webapp/you/',
  'webapp/'
];

// ignore: must_be_immutable
class WebViewWidget extends StatefulWidget {
  /// 数据模型
  final CommonItemModel itemModel;

  /// 是否是第一次加载
  bool _isFirstPush = true;
  WebViewWidget({@required this.itemModel});

  @override
  _WebViewWidgetState createState() => _WebViewWidgetState();
}

class _WebViewWidgetState extends State<WebViewWidget> {
  final _flutterWebviewPlugin = FlutterWebviewPlugin();
  StreamSubscription<WebViewHttpError> _onError;
  StreamSubscription<WebViewStateChanged> _onStateChanged;
  StreamSubscription<double> _onScrollYChanged;
  bool _isPop = false;

  @override
  void initState() {
    super.initState();
    // 错误监听
    _onError =
        _flutterWebviewPlugin.onHttpError.listen((WebViewHttpError error) {
      if (int.parse(error.code) != 200) {
        print('加载: ' + error.url + ' 失败!');
      }
    });

    // 状态改变监听
    _onStateChanged = _flutterWebviewPlugin.onStateChanged
        .listen((WebViewStateChanged state) {
      if (state.type == WebViewState.shouldStart) {
        if (_isIgnore(url: state.url) && !_isPop && !widget._isFirstPush) {
          _isPop = true;
          _flutterWebviewPlugin.close();
          Navigator.of(context).pop();
        }
      } else if (state.type == WebViewState.finishLoad) {
        widget._isFirstPush = false; // 已经展示网页 将标记置位false
      }
    });

    _onScrollYChanged =
        _flutterWebviewPlugin.onScrollYChanged.listen((scrollY) {});
  }

  @override
  void dispose() {
    _onError.cancel();
    _onStateChanged.cancel();
    _onScrollYChanged.cancel();
    _flutterWebviewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double topMargin = MediaQuery.of(context).padding.top; // 导航栏顶部安全距离
    return Scaffold(
        body: Column(
      children: <Widget>[
        _appBar(context: context),
        Expanded(
            child: WebviewScaffold(
          url: widget.itemModel.url,
          withZoom: true,
          withLocalStorage: true,
          withJavascript: true,
          hidden: true,
        ))
      ],
    ));
  }

  Widget _appBar({@required BuildContext context}) {
    String statusBarColorStr = widget.itemModel.statusBarColor ?? 'ffffff';
    Color titleColor =
        (statusBarColorStr == 'ffffff' ? Colors.black : Colors.white);
    double topMargin = MediaQuery.of(context).padding.top; // 导航栏顶部安全距离
    if (widget.itemModel.hideAppBar ?? false) {
      // 隐藏导航栏
      return Container(
        height: topMargin,
        color: Color(
            int.parse('0xff' + (widget.itemModel.statusBarColor ?? 'ffffff'))),
      );
    }

    // 显示状态栏
    return Container(
        padding: EdgeInsets.only(top: topMargin),
        color: Color(int.parse('0xff' + statusBarColorStr)),
        height: 44 + topMargin,
        child: Stack(children: <Widget>[
          Align(
              alignment: Alignment.center,
              child: Text(widget.itemModel.title ?? '',
                  style: TextStyle(color: titleColor, fontSize: 20.0))),
          Align(
              alignment: Alignment(-1, 0),
              child: IconButton(
                  icon: Icon(
                    Icons.close,
                    color: titleColor,
                  ),
                  onPressed: () {
                    _flutterWebviewPlugin.close();
                    Navigator.of(context).pop();
                  }))
        ]));
  }

  bool _isIgnore({@required String url}) {
    bool ignore = false;
    for (String str in ignoreURLs) {
      if (url.endsWith(str)) {
        ignore = true;
        break;
      }
    }
    return ignore;
  }
}
